import { defineComponent, reactive, toRefs, computed } from "vue"
import VeCheckbox from "amtf/components/checkbox"
import { COMPS_NAME, EMIT_EVENTS } from "../util/constant"
import { inject } from "vue"

import emitter from "amtf/utils/emitter"
import { useEmitter } from "amtf/hooks"

import { use样式 } from "amtf/hooks"
import { isNumber, isEmptyValue, getValByUnit, 拼组件名, isFunction, isBoolean, getRandomId } from "amtf/utils"
const 主名 = "table-body-checkbox-content"
const 组件名 = 拼组件名(主名)

export default defineComponent({
    name: 组件名,
    props: {
        checkboxOption: {
            type: Object,
            default: () => null,
        },
        rowKey: {
            type: [String, Number],
            required: true,
        },
        internalCheckboxSelectedRowKeys: {
            type: Array,
            default: () => null,
        },
    },
    setup(props) {
        const { dispatch } = useEmitter(inject("bodyid"))
        const { 拼样式名_table直属 } = use样式(主名)

        const state = reactive({
            isSelected: false,
        })

        const disabled = computed(() => {
            let result = false
            const { checkboxOption, rowKey } = props
            if (!checkboxOption) {
                return
            }
            const { disableSelectedRowKeys } = checkboxOption
            if (Array.isArray(disableSelectedRowKeys) && disableSelectedRowKeys.includes(rowKey)) {
                result = true
            }
            return result
        })

        const isControlledProp = computed(() => {
            const { checkboxOption } = props
            return checkboxOption && Array.isArray(checkboxOption.selectedRowKeys)
        })

        watch(
            () => props.internalCheckboxSelectedRowKeys,
            () => {
                state.isSelected = initSelected()
            },
            { immediate: true }
        )

        function initSelected() {
            let result = false
            const { rowKey, internalCheckboxSelectedRowKeys } = props
            if (Array.isArray(internalCheckboxSelectedRowKeys) && internalCheckboxSelectedRowKeys.includes(rowKey)) {
                result = true
            }
            return result
        }

        function selectedChange(isSelected) {
            const { isControlledProp } = state
            // 非受控
            if (!isControlledProp) {
                state.isSelected = isSelected
            }
            dispatch(EMIT_EVENTS.CHECKBOX_SELECTED_ROW_CHANGE, {
                rowKey: props.rowKey,
                isSelected,
            })
        }

        return () => (
            <VeCheckbox
                class={拼样式名_table直属("checkbox-wrapper")}
                {...{
                    isControlled: true,
                    isSelected: state.isSelected,
                    disabled: disabled.value,
                    onCheckedChange: isSelected => selectedChange(isSelected),
                }}
            />
        )
    },
})
